<template>
  <view class="select-seat-page">
    <!-- Header -->
    <view class="header-bar">
      <view class="back-icon" @tap="goBack">
        <image src="/static/images/back-arrow-white.png" mode="aspectFit" />
      </view>
      <view class="header-content">
        <view class="cinema-name">{{ cinemaInfo.name }}</view>
        <view class="movie-info-brief">
          {{ movieInfo.name }} {{ scheduleInfo.showDate | dateFilter }} {{ scheduleInfo.showTime }}
        </view>
      </view>
    </view>

    <!-- Seat Map Area -->
    <view class="seat-map-container">
      <view class="screen-info">
        <view class="screen-text">{{ scheduleInfo.hallName }} 银幕</view>
      </view>

      <view class="seat-legend">
        <view class="legend-item">
          <image src="/static/images/seat-available.png" class="seat-icon" />
          <text>可选</text>
        </view>
        <view class="legend-item">
          <image src="/static/images/seat-sold.png" class="seat-icon" />
          <text>不可选</text>
        </view>
        <view class="legend-item">
          <image src="/static/images/seat-selected.png" class="seat-icon" />
          <text>已选</text>
        </view>
      </view>

      <scroll-view scroll-x scroll-y class="seat-scroll-view">
        <view class="seat-grid">
          <view v-for="(row, rowIndex) in seatLayout" :key="rowIndex" class="seat-row">
            <view class="row-number">{{ rowIndex + 1 }}</view>
            <view
              v-for="(seat, seatIndex) in row"
              :key="seatIndex"
              class="seat-wrapper"
              @tap="handleSelectSeat(rowIndex, seatIndex)"
            >
              <image :src="getSeatIcon(seat)" class="seat-icon-map" />
            </view>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- Bottom Bar -->
    <view class="bottom-bar">
      <view class="selected-seats-info" v-if="selectedSeats.length > 0">
         <view class="selected-seat-item" v-for="(seat, index) in selectedSeats" :key="index">
            <text class="seat-position">{{ seat.row + 1 }}排{{ seat.col + 1 }}座</text>
            <text class="seat-price">¥{{ scheduleInfo.price.toFixed(2) }}</text>
            <view class="close-icon" @tap="cancelSelectedSeat(seat.row, seat.col)"></view>
        </view>
      </view>
      <button
        class="confirm-btn"
        :class="{ disabled: selectedSeats.length === 0 }"
        @tap="confirmSelection"
      >
        {{ selectedSeats.length > 0 ? `¥${totalPrice.toFixed(2)} 确认选座` : '请先选座' }}
      </button>
    </view>
  </view>
</template>

<script>
// Seat Status: 0 = available, 1 = sold, 2 = selected
const SEAT_AVAILABLE = 0;
const SEAT_SOLD = 1;
const SEAT_SELECTED = 2;
const MAX_SEATS = 4;

export default {
  data() {
    return {
      scheduleId: null,
      cinemaInfo: {},
      movieInfo: {},
      scheduleInfo: {},
      seatLayout: [], // 2D array representing the seat map
      selectedSeats: [], // Array of {row, col}
    };
  },
  computed: {
    totalPrice() {
      return this.selectedSeats.length * (this.scheduleInfo.price || 0);
    }
  },
  onLoad(options) {
    if (options.schedule_id) {
      this.scheduleId = options.schedule_id;
      this.loadScheduleDetails();
    }
  },
  methods: {
    goBack() {
      uni.navigateBack();
    },
    async loadScheduleDetails() {
      // Fetch schedule, which includes hall info, movie info, cinema info
      const res = await uni.request({
        url: `http://localhost:9090/findOneSchedule?id=${this.scheduleId}`,
      });

      if (res[1].data.code === 1) {
        this.scheduleInfo = res[1].data.schedule;
        
        // Fetch related info in parallel
        this.loadMovieInfo(this.scheduleInfo.movieId);
        this.loadCinemaInfo(this.scheduleInfo.cinemaId);
        
        // Create the seat layout
        this.initSeatLayout();
      } else {
        uni.showToast({ title: '加载排片信息失败', icon: 'none' });
      }
    },
    loadMovieInfo(movieId) {
        uni.request({
            url: `http://localhost:9090/findOneMovie?id=${movieId}`,
            success: (res) => { if (res.data.code === 1) this.movieInfo = res.data.movie; }
        });
    },
    loadCinemaInfo(cinemaId) {
        uni.request({
            url: `http://localhost:9090/selectCinemaInfo?id=${cinemaId}`,
            success: (res) => { if (res.data.code === 1) this.cinemaInfo = res.data.cinema; }
        });
    },
    initSeatLayout() {
      // Assuming a fixed size hall for now, e.g., 8 rows x 10 cols
      // In a real app, this should come from the hall info
      const rows = 8;
      const cols = 10;
      const layout = Array(rows).fill(0).map(() => Array(cols).fill(SEAT_AVAILABLE));

      // Mark sold seats
      const soldSeats = JSON.parse(this.scheduleInfo.seatInfo || '[]');
      soldSeats.forEach(seatIdentifier => {
          // Identifier is 1-based, e.g., 1-10 for row 1, 11-20 for row 2
          const zeroBasedIndex = seatIdentifier - 1;
          const row = Math.floor(zeroBasedIndex / cols);
          const col = zeroBasedIndex % cols;
          if (row < rows && col < cols) {
              layout[row][col] = SEAT_SOLD;
          }
      });
      this.seatLayout = layout;
    },
    getSeatIcon(status) {
        switch(status) {
            case SEAT_AVAILABLE: return '/static/images/seat-available.png';
            case SEAT_SOLD: return '/static/images/seat-sold.png';
            case SEAT_SELECTED: return '/static/images/seat-selected.png';
            default: return '/static/images/seat-available.png';
        }
    },
    handleSelectSeat(rowIndex, seatIndex) {
      const currentStatus = this.seatLayout[rowIndex][seatIndex];
      
      if (currentStatus === SEAT_SOLD) {
        return; // Cannot select sold seats
      }
      
      if (currentStatus === SEAT_AVAILABLE) {
        if (this.selectedSeats.length >= MAX_SEATS) {
          uni.showToast({ title: `一次最多选择${MAX_SEATS}个座位`, icon: 'none' });
          return;
        }
        this.seatLayout[rowIndex][seatIndex] = SEAT_SELECTED;
        this.selectedSeats.push({ row: rowIndex, col: seatIndex });
      } else if (currentStatus === SEAT_SELECTED) {
        this.seatLayout[rowIndex][seatIndex] = SEAT_AVAILABLE;
        this.selectedSeats = this.selectedSeats.filter(
          seat => seat.row !== rowIndex || seat.col !== seatIndex
        );
      }
      // Force re-render
      this.$forceUpdate();
    },
    cancelSelectedSeat(rowIndex, colIndex) {
        this.handleSelectSeat(rowIndex, colIndex);
    },
    confirmSelection() {
      if (this.selectedSeats.length === 0) {
        uni.showToast({ title: '请先选择座位', icon: 'none' });
        return;
      }
      
      // Prepare selected seat data to send to the backend
      const selectedSeatIdentifiers = this.selectedSeats.map(seat => {
          return seat.row * 10 + seat.col + 1; // Assuming 10 cols
      });
      
      // Navigate to order confirmation page
      uni.navigateTo({
          url: `/pages/submit-order/submit-order?schedule_id=${this.scheduleId}&seats=${JSON.stringify(selectedSeatIdentifiers)}`
      });
    }
  },
  filters: {
    dateFilter(dateStr) {
      if (!dateStr) return '';
      const parts = String(dateStr).split('-');
      return `${parts[0]}年${parts[1]}月${parts[2]}日`;
    }
  }
};
</script>

<style>
/* Page layout */
.select-seat-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f7f7f7;
}
.header-bar {
  position: fixed; top: 0; left: 0; right: 0;
  height: 120rpx;
  background-color: #dd2727;
  color: #fff;
  display: flex;
  align-items: center;
  padding: 0 20rpx;
  z-index: 100;
}
.back-icon { width: 40rpx; height: 40rpx; }
.back-icon image { width: 100%; height: 100%; }
.header-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin-right: 40rpx; /* balance the back icon */
}
.cinema-name { font-size: 32rpx; font-weight: bold; }
.movie-info-brief { font-size: 24rpx; opacity: 0.9; margin-top: 5rpx; }

/* Seat Map */
.seat-map-container {
  margin-top: 120rpx; /* Header height */
  flex: 1;
  display: flex;
  flex-direction: column;
}
.screen-info { padding: 20rpx; text-align: center; }
.screen-text {
  display: inline-block;
  background-color: #dcdcdc;
  color: #333;
  padding: 5rpx 80rpx;
  border-bottom-left-radius: 20rpx;
  border-bottom-right-radius: 20rpx;
}
.seat-legend {
  display: flex;
  justify-content: center;
  padding: 20rpx;
  gap: 40rpx;
}
.legend-item { display: flex; align-items: center; gap: 10rpx; font-size: 24rpx;}
.seat-icon { width: 40rpx; height: 40rpx; }

.seat-scroll-view {
  width: 100%;
  flex: 1;
}
.seat-grid {
  display: inline-flex;
  flex-direction: column;
  align-items: center;
  padding: 20rpx;
}
.seat-row {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}
.row-number {
  width: 40rpx;
  text-align: center;
  color: #999;
  font-size: 24rpx;
}
.seat-wrapper {
  margin: 0 5rpx;
}
.seat-icon-map {
  width: 50rpx;
  height: 50rpx;
}

/* Bottom Bar */
.bottom-bar {
  position: fixed; bottom: 0; left: 0; right: 0;
  background-color: #fff;
  border-top: 1rpx solid #e0e0e0;
  padding: 20rpx;
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
  box-shadow: 0 -2rpx 10rpx rgba(0,0,0,0.05);
}
.selected-seats-info {
    display: flex;
    flex-wrap: wrap;
    gap: 20rpx;
    margin-bottom: 20rpx;
}
.selected-seat-item {
    background-color: #ffeceb;
    border: 1rpx solid #dd2727;
    border-radius: 8rpx;
    padding: 10rpx 15rpx;
    font-size: 24rpx;
    position: relative;
    padding-right: 40rpx;
}
.seat-position { color: #333; }
.seat-price { color: #dd2727; margin-left: 10rpx; }
.close-icon {
    position: absolute;
    right: 5rpx;
    top: 50%;
    transform: translateY(-50%);
    width: 30rpx;
    height: 30rpx;
    background-color: #dd2727;
    color: #fff;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
}
.close-icon::after {
    content: '×';
    font-size: 24rpx;
    line-height: 30rpx;
}

.confirm-btn {
  width: 100%;
  height: 88rpx;
  line-height: 88rpx;
  background-color: #dd2727;
  color: #fff;
  font-size: 32rpx;
  border-radius: 44rpx;
}
.confirm-btn.disabled {
  background-color: #e0e0e0;
  color: #999;
}
</style>